﻿using GBT_Tool_v4._0.ToolHelps;
using Newtonsoft.Json.Linq;
using NLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using TakeFoodSystem.Business;
using TakeFoodSystem.Entity;

namespace TakeFoodSystem
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private Logger logger = LogManager.GetCurrentClassLogger();
        //实时读写配置文件，写入时需要记得调用 cfa.Save()
        Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        Tools tools = new Tools();
        int companyID = int.Parse(ConfigurationManager.AppSettings["companyID"]);
        int districtID = int.Parse(ConfigurationManager.AppSettings["districtID"]);
        int hallID = int.Parse(ConfigurationManager.AppSettings["hallID"]);
        bool ModifyPrice = bool.Parse(ConfigurationManager.AppSettings["ModifyPrice"]);
        bool IsAutoStart = bool.Parse(ConfigurationManager.AppSettings["AutoStart"]);
        string scanText = "";
        string inputStr = "";
        OptTakeFoodRecord optTakeFoodRecord = new OptTakeFoodRecord();
        int totalPage = 0;
        int totalNumber = 0;
        int pageSize = 26;
        int pageIndex = 1;
        System.Windows.Forms.Screen[] screens = System.Windows.Forms.Screen.AllScreens;
        List<Window> openWindows = new List<Window>();
        private ScanerHook listener = new ScanerHook();

        public MainWindow()
        {
            InitializeComponent();
            listener.ScanerEvent += Listener_ScanerEvent;
        }

        private void Listener_ScanerEvent(ScanerHook.ScanerCodes codes)
        {
            scanText = codes.Result;
            if (string.IsNullOrEmpty(scanText))
            {
                optTakeFoodRecord.Speak("请扫码");
                message.Content = "请扫码";
                return;
            }

            _loading.Visibility = Visibility.Visible;
            inputStr = scanText;
            scanText = "";

            //执行扫描任务
            Task task = new Task(new Action(delegate {
                JObject joParam = new JObject();
                joParam["districtID"] = districtID;
                joParam["UUID"] = inputStr.Substring(6, inputStr.Length - 6);
                joParam["UserID"] = int.Parse(inputStr.Substring(0, 6));
                joParam["HallID"] = hallID;
                joParam["Creator"] = Global.MealUser.UserID;
                string msg = "";
                var list = optTakeFoodRecord.AddOrModifyTakeFoodRecord(joParam, ref msg);
                message.Dispatcher.Invoke(new Action(delegate {
                    message.Content = msg;
                }));
                pageIndex = 1;
                //刷新取餐记录
                GetData(pageIndex);
            }));
            task.Start();
            task.ContinueWith((t) => {
                _loading.Dispatcher.Invoke(new Action(delegate {
                    txtPageIndex.Text = pageIndex.ToString();
                    _loading.Visibility = Visibility.Collapsed;
                }));
            });
        }

        private string GetData(int pageIndex, int hallID = 0, int mealID = 0)
        {
            JObject joParam = new JObject();
            joParam["districtID"] = districtID;
            joParam["pageIndex"] = pageIndex;
            joParam["pageSize"] = pageSize;
            if (hallID == 0)
            {
                hallID = int.Parse(cfa.AppSettings.Settings["hallID"].Value);
            }
            joParam["HallID"] = hallID;
            joParam["MealID"] = mealID;
            joParam["Creator"] = Global.MealUser.UserID;
            string msg = "";
            Global.ObservableCollection = optTakeFoodRecord.GetTakeFoodRecordList(joParam, ref totalPage, ref totalNumber, ref msg);
            lvTakeFood.Dispatcher.Invoke(new Action(delegate {
                lvTakeFood.ItemsSource = Global.ObservableCollection;
                total.Content = "第 " + totalPage + " 页，共 " + totalNumber + " 条记录。";
            }));
            return msg;
        }

        private void GetCompany(string companyName)
        {
            JArray jaResult = optTakeFoodRecord.GetCompanyInfo(companyName);
            List<SelectedItem> selectedItems = new List<SelectedItem>();
            for (int index = 0; index < jaResult.Count; index++)
            {
                selectedItems.Add(new SelectedItem {
                    ID = (int)jaResult[index]["id"],
                    Name = (string)jaResult[index]["name"]
                });
            }
            cbCompany.Dispatcher.Invoke(new Action(delegate {
                cbCompany.ItemsSource = selectedItems;
                cbCompany.SelectedValue = companyID;
            }));
        }

        private void GetDistrict(int companyID)
        {
            JArray jaResult = optTakeFoodRecord.GetDistrictInfo(companyID);
            List<SelectedItem> selectedItems = new List<SelectedItem>();
            for (int index = 0; index < jaResult.Count; index++)
            {
                selectedItems.Add(new SelectedItem
                {
                    ID = (int)jaResult[index]["id"],
                    Name = (string)jaResult[index]["name"]
                });
            }
            cbDistrict.Dispatcher.Invoke(new Action(delegate {
                cbDistrict.ItemsSource = selectedItems;
                cbDistrict.SelectedValue = districtID;
            }));
        }

        private void GetHall(int districtID)
        {
            JArray jaResult = optTakeFoodRecord.GetHallInfo(districtID);
            List<SelectedItem> selectedItems = new List<SelectedItem>();
            if (jaResult != null)
            {
                for (int index = 0; index < jaResult.Count; index++)
                {
                    selectedItems.Add(new SelectedItem
                    {
                        ID = (int)jaResult[index]["id"],
                        Name = (string)jaResult[index]["name"]
                    });
                }
                cbHall.Dispatcher.Invoke(new Action(delegate
                {
                    cbHall.ItemsSource = selectedItems;
                    cbHall.SelectedValue = hallID;

                    cbSearchHall.ItemsSource = selectedItems;
                    cbSearchHall.SelectedIndex = 0;
                }));
            }
            else
            {
                cbHall.Dispatcher.Invoke(new Action(delegate
                {
                    cbHall.ItemsSource = null;
                    cbSearchHall.ItemsSource = null;
                }));
            }
        }

        private void GetMealTime(int districtID)
        {
            JArray jaResult = optTakeFoodRecord.GetMealTimeInfo(districtID);
            List<SelectedItem> selectedItems = new List<SelectedItem>();
            if (jaResult != null)
            {
                for (int index = 0; index < jaResult.Count; index++)
                {
                    selectedItems.Add(new SelectedItem
                    {
                        ID = (int)jaResult[index]["id"],
                        Name = (string)jaResult[index]["name"]
                    });
                }
                cbSearchMealTime.Dispatcher.Invoke(new Action(delegate
                {
                    cbSearchMealTime.ItemsSource = selectedItems;
                    cbSearchMealTime.SelectedIndex = 0;
                }));
            }
            else
            {
                cbSearchMealTime.Dispatcher.Invoke(new Action(delegate
                {
                    cbSearchMealTime.ItemsSource = null;
                }));
            }
        }

        private void WTakeFoodSystem_Loaded(object sender, RoutedEventArgs e)
        {
            listener.Start();
            openWindows.Clear();
            // 设置全屏
            this.WindowState = WindowState.Normal;
            this.WindowStyle = WindowStyle.None;
            this.ResizeMode = ResizeMode.NoResize;
            //this.Topmost = true;

            this.Left = 0.0;
            this.Top = 0.0;
            this.Width = SystemParameters.PrimaryScreenWidth;
            this.Height = SystemParameters.PrimaryScreenHeight;
            message.Width = SystemParameters.PrimaryScreenWidth - 335;

            lvTakeFood.FontSize = double.Parse(cfa.AppSettings.Settings["FontSize"].Value);
            //txtScan.Focus();
            
            if (ModifyPrice)
            {
                cbModifyPrice.IsChecked = true;
                Modify.Visibility = Visibility.Visible;
            }
            else
            {
                cbModifyPrice.IsChecked = false;
                Modify.Visibility = Visibility.Collapsed;
            }

            if (IsAutoStart)
            {
                cbAutoStart.IsChecked = true;
            }
            else
            {
                cbAutoStart.IsChecked = false;
            }

            //获取取餐记录数据
            _loading.Visibility = Visibility.Visible;
            string msg = "";
            Task task = new Task(new Action(delegate {
                pageIndex = 1;
                msg = GetData(pageIndex);
                GetCompany("");
                GetDistrict(companyID);
                GetHall(districtID);
                GetMealTime(districtID);
            }));
            task.Start();
            task.ContinueWith((t) => {
                _loading.Dispatcher.Invoke(new Action(delegate {
                    txtPageIndex.Text = pageIndex.ToString();
                    _loading.Visibility = Visibility.Collapsed;
                    message.Content = msg;
                    openWindows.Add(this);

                    var mainScreen = screens.FirstOrDefault(x => x.Primary == true);
                    System.Drawing.Rectangle mswa = mainScreen.WorkingArea;

                    //多扩展屏时 扩展屏展示数据列表
                    if (screens.Length > 1)
                    {
                        var subScreens = (from o in screens where o.Primary == false select o).ToList();
                        foreach (System.Windows.Forms.Screen subScreen in subScreens)
                        {
                            System.Drawing.Rectangle mswa2 = subScreen.WorkingArea;
                            ViceScreen viceScreen = new ViceScreen();
                            viceScreen.WindowStartupLocation = WindowStartupLocation.Manual;
                            viceScreen.Left = mswa2.Left;
                            viceScreen.Top = mswa2.Top;
                            viceScreen.Width = mswa2.Width;
                            viceScreen.Height = mswa2.Height;
                            openWindows.Add(viceScreen);
                            viceScreen.Show();
                        }
                    }
                }));
                //this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => { Keyboard.Focus(txtScan); }));
            });
        }

        private void Search_Click(object sender, RoutedEventArgs e)
        {
            if (SearchBox.Visibility == Visibility.Collapsed)
            {
                SearchBox.Visibility = Visibility.Visible;
            }
            else
            {
                SearchBox.Visibility = Visibility.Collapsed;
            }
            //this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => { Keyboard.Focus(txtScan); }));
        }

        private void BtnFirstPage_Click(object sender, RoutedEventArgs e)
        {
            //获取取餐记录数据
            _loading.Visibility = Visibility.Visible;
            string msg = "";
            Task task = new Task(new Action(delegate {
                pageIndex = 1;
                msg = GetData(pageIndex);
            }));
            task.Start();
            task.ContinueWith((t) => {
                _loading.Dispatcher.Invoke(new Action(delegate {
                    txtPageIndex.Text = pageIndex.ToString();
                    _loading.Visibility = Visibility.Collapsed;
                    message.Content = msg;
                }));
                //this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => { Keyboard.Focus(txtScan); }));
            });
        }

        private void BtnPageUp_Click(object sender, RoutedEventArgs e)
        {
            //获取取餐记录数据
            _loading.Visibility = Visibility.Visible;
            string msg = "";
            Task task = new Task(new Action(delegate {
                if(pageIndex > 1)
                {
                    pageIndex--;
                    msg = GetData(pageIndex);
                }
            }));
            task.Start();
            task.ContinueWith((t) => {
                _loading.Dispatcher.Invoke(new Action(delegate {
                    txtPageIndex.Text = pageIndex.ToString();
                    _loading.Visibility = Visibility.Collapsed;
                    message.Content = msg;
                }));
                //this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => { Keyboard.Focus(txtScan); }));
            });
        }

        private void BtnSkip_Click(object sender, RoutedEventArgs e)
        {
            //获取取餐记录数据
            _loading.Visibility = Visibility.Visible;
            string msg = "";
            if (!string.IsNullOrWhiteSpace(txtPageIndex.Text.Trim()) && int.Parse(txtPageIndex.Text.Trim()) > 0)
            {
                pageIndex = int.Parse(txtPageIndex.Text.Trim());
            }
            else
            {
                _loading.Visibility = Visibility.Collapsed;
                return;
            }
            Task task = new Task(new Action(delegate {
                msg = GetData(pageIndex);
            }));
            task.Start();
            task.ContinueWith((t) => {
                _loading.Dispatcher.Invoke(new Action(delegate {
                    txtPageIndex.Text = pageIndex.ToString();
                    _loading.Visibility = Visibility.Collapsed;
                    message.Content = msg;
                }));
                //this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => { Keyboard.Focus(txtScan); }));
            });
        }

        private void BtnNextPage_Click(object sender, RoutedEventArgs e)
        {
            //获取取餐记录数据
            _loading.Visibility = Visibility.Visible;
            string msg = "";
            Task task = new Task(new Action(delegate {
                if (pageIndex < totalPage)
                {
                    pageIndex++;
                    msg = GetData(pageIndex);
                }
            }));
            task.Start();
            task.ContinueWith((t) => {
                _loading.Dispatcher.Invoke(new Action(delegate {
                    txtPageIndex.Text = pageIndex.ToString();
                    _loading.Visibility = Visibility.Collapsed;
                    message.Content = msg;
                }));
            });
        }

        private void BtnEndPage_Click(object sender, RoutedEventArgs e)
        {
            //获取取餐记录数据
            _loading.Visibility = Visibility.Visible;
            string msg = "";
            Task task = new Task(new Action(delegate {
                if (pageIndex > 0 && pageIndex < totalPage)
                {
                    pageIndex = totalPage;
                    msg = GetData(pageIndex);
                }
            }));
            task.Start();
            task.ContinueWith((t) => {
                _loading.Dispatcher.Invoke(new Action(delegate {
                    txtPageIndex.Text = pageIndex.ToString();
                    _loading.Visibility = Visibility.Collapsed;
                    message.Content = msg;
                }));
            });
        }

        private void Setting_Click(object sender, RoutedEventArgs e)
        {
            if (SettingBox.Visibility == Visibility.Collapsed)
            {
                SettingBox.Visibility = Visibility.Visible;
            }
            else
            {
                SettingBox.Visibility = Visibility.Collapsed;
            }
            //this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => { Keyboard.Focus(txtScan); }));
        }

        private void Modify_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Delete_Click(object sender, RoutedEventArgs e)
        {

        }

        private void TxtScan_KeyUp(object sender, KeyEventArgs e)
        {
            //if (e.Key == Key.Enter)
            //{
            //    if (string.IsNullOrEmpty(txtScan.Text.Trim()))
            //    {
            //        optTakeFoodRecord.Speak("请扫码");
            //        message.Content = "请扫码";
            //        return;
            //    }

            //    _loading.Visibility = Visibility.Visible;
            //    inputStr = txtScan.Text.Trim();
            //    txtScan.Text = "";

            //    //执行扫描任务
            //    Task task = new Task(new Action(delegate {
            //        JObject joParam = new JObject();
            //        joParam["districtID"] = districtID;
            //        joParam["UUID"] = inputStr.Substring(6, inputStr.Length - 6);
            //        joParam["UserID"] = int.Parse(inputStr.Substring(0, 6));
            //        joParam["HallID"] = hallID;
            //        joParam["Creator"] = Global.MealUser.UserID;
            //        string msg = "";
            //        var list = optTakeFoodRecord.AddOrModifyTakeFoodRecord(joParam, ref msg);
            //        message.Dispatcher.Invoke(new Action(delegate {
            //            message.Content = msg;
            //        }));
            //        pageIndex = 1;
            //        //刷新取餐记录
            //        GetData(pageIndex);
            //    }));
            //    task.Start();
            //    task.ContinueWith((t) => {
            //        _loading.Dispatcher.Invoke(new Action(delegate {
            //            txtPageIndex.Text = pageIndex.ToString();
            //            _loading.Visibility = Visibility.Collapsed;
            //        }));
            //    });
            //}
        }

        private void WTakeFoodSystem_KeyUp(object sender, KeyEventArgs e)
        {
            //this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => { Keyboard.Focus(txtScan); }));
        }

        private void WTakeFoodSystem_TouchDown(object sender, TouchEventArgs e)
        {
            //this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => { Keyboard.Focus(txtScan); }));
        }

        private void WTakeFoodSystem_TouchUp(object sender, TouchEventArgs e)
        {
            //this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => { Keyboard.Focus(txtScan); }));
        }

        private void CommandBinding_Increase_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (lvTakeFood.FontSize > 50)
            {
                e.CanExecute = false;
            }
            else
            {
                e.CanExecute = true;
            }
        }

        private void CommandBinding_Increase_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            lvTakeFood.FontSize += 5;
            cfa.AppSettings.Settings["FontSize"].Value = lvTakeFood.FontSize.ToString();
            cfa.Save();
            //this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => { Keyboard.Focus(txtScan); }));
        }

        private void CommandBinding_Decrease_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (lvTakeFood.FontSize <= 5)
            {
                e.CanExecute = false;
            }
            else
            {
                e.CanExecute = true;
            }
        }

        private void CommandBinding_Decrease_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            lvTakeFood.FontSize -= 5;
            cfa.AppSettings.Settings["FontSize"].Value = lvTakeFood.FontSize.ToString();
            cfa.Save();
            //this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => { Keyboard.Focus(txtScan); }));
        }

        private void LoginOut_Click(object sender, RoutedEventArgs e)
        {
            Login login = new Login();
            login.Show();
            if (openWindows.Count > 0)
            {
                foreach (var item in openWindows)
                {
                    item.Close();
                }
            }
        }

        // 锁定计算机.   
        [DllImport("user32.dll")]
        private static extern void LockWorkStation();//须写extern

        private void SystemLock_Click(object sender, RoutedEventArgs e)
        {
            LockWorkStation();
        }

        //注销计算机
        [DllImport("user32.dll", EntryPoint = "ExitWindowsEx", CharSet = CharSet.Ansi)]
        private static extern int ExitWindowsEx(int a, int b);

        private void SystemOut_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.DialogResult dialogResult = System.Windows.Forms.MessageBox.Show("确定注销电脑", "温馨提示", System.Windows.Forms.MessageBoxButtons.OKCancel, System.Windows.Forms.MessageBoxIcon.Information);
            if (dialogResult == System.Windows.Forms.DialogResult.OK)
            {
                ExitWindowsEx(0, 0);
            }
            else
            {
                //this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => { Keyboard.Focus(txtScan); }));
            }
        }

        private void SystemRestart_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.DialogResult dialogResult = System.Windows.Forms.MessageBox.Show("确定重启电脑", "温馨提示", System.Windows.Forms.MessageBoxButtons.OKCancel, System.Windows.Forms.MessageBoxIcon.Information);
            if (dialogResult == System.Windows.Forms.DialogResult.OK)
            {
                System.Diagnostics.Process mp = new System.Diagnostics.Process();
                mp.StartInfo.FileName = "cmd.exe";
                mp.StartInfo.RedirectStandardInput = true;
                mp.StartInfo.RedirectStandardOutput = true;
                mp.StartInfo.RedirectStandardError = true;
                mp.StartInfo.UseShellExecute = false;
                mp.StartInfo.CreateNoWindow = true;
                mp.Start();//启动进程
                mp.StandardInput.WriteLine("shutdown -r -t 0");//重启
            }
            else
            {
                //this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => { Keyboard.Focus(txtScan); }));
            }
        }

        private void SystemClose_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.DialogResult dialogResult = System.Windows.Forms.MessageBox.Show("确定关闭电脑", "温馨提示", System.Windows.Forms.MessageBoxButtons.OKCancel, System.Windows.Forms.MessageBoxIcon.Information);
            if (dialogResult == System.Windows.Forms.DialogResult.OK)
            {
                System.Diagnostics.Process mp = new System.Diagnostics.Process();
                mp.StartInfo.FileName = "cmd.exe";
                mp.StartInfo.RedirectStandardInput = true;
                mp.StartInfo.RedirectStandardOutput = true;
                mp.StartInfo.RedirectStandardError = true;
                mp.StartInfo.UseShellExecute = false;
                mp.StartInfo.CreateNoWindow = true;
                mp.Start();//启动进程
                mp.StandardInput.WriteLine("shutdown -s -t 0");//关机
            }
            else
            {
                //this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => { Keyboard.Focus(txtScan); }));
            }
        }

        private void CommandBinding_ShowCompany_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void CommandBinding_ShowCompany_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (lblCompany.Visibility == Visibility.Visible)
            {
                lblCompany.Visibility = Visibility.Collapsed;
                cbCompany.Visibility = Visibility.Collapsed;
                cbModifyPrice.Visibility = Visibility.Collapsed;
            }
            else
            {
                lblCompany.Visibility = Visibility.Visible;
                cbCompany.Visibility = Visibility.Visible;
                cbModifyPrice.Visibility = Visibility.Visible;
            }
            //this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => { Keyboard.Focus(txtScan); }));
        }

        private void BtnSettingClose_Click(object sender, RoutedEventArgs e)
        {
            SettingBox.Visibility = Visibility.Collapsed;
            //this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => { Keyboard.Focus(txtScan); }));
        }

        private void CbModifyPrice_Click(object sender, RoutedEventArgs e)
        {
            if (cbModifyPrice.IsChecked == true)
            {
                cfa.AppSettings.Settings["ModifyPrice"].Value = "true";
                Modify.Visibility = Visibility.Visible;
            }
            else
            {
                cfa.AppSettings.Settings["ModifyPrice"].Value = "false";
                Modify.Visibility = Visibility.Collapsed;
            }
            cfa.Save();
        }

        private void CbAutoStart_Click(object sender, RoutedEventArgs e)
        {
            if (cbAutoStart.IsChecked == true)
            {
                cfa.AppSettings.Settings["AutoStart"].Value = "true";
                MessageBox.Show(tools.AutoStart(), "温馨提示");
            }
            else
            {
                cfa.AppSettings.Settings["AutoStart"].Value = "false";
                MessageBox.Show(tools.UnAutoStart(), "温馨提示");
            }
            cfa.Save();
        }

        private void CbCompany_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if(cbCompany.SelectedValue != null)
            {
                cfa.AppSettings.Settings["companyID"].Value = cbCompany.SelectedValue.ToString();
                cfa.Save();

                companyID = (int)cbCompany.SelectedValue;
                _loading.Visibility = Visibility.Visible;
                Task task = new Task(new Action(delegate {
                    GetDistrict(companyID);
                }));
                task.Start();
                task.ContinueWith((t) => {
                    _loading.Dispatcher.Invoke(new Action(delegate {
                        _loading.Visibility = Visibility.Collapsed;
                        
                        cbHall.ItemsSource = null;
                        cbSearchHall.ItemsSource = null;
                        cbSearchMealTime.ItemsSource = null;
                    }));
                });
            }
        }

        private void CbDistrict_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (cbDistrict.SelectedValue != null)
            {
                cfa.AppSettings.Settings["districtID"].Value = cbDistrict.SelectedValue.ToString();
                cfa.Save();

                districtID = (int)cbDistrict.SelectedValue;
                _loading.Visibility = Visibility.Visible;
                Task task = new Task(new Action(delegate {
                    GetHall(districtID);
                    GetMealTime(districtID);
                }));
                task.Start();
                task.ContinueWith((t) => {
                    _loading.Dispatcher.Invoke(new Action(delegate {
                        _loading.Visibility = Visibility.Collapsed;
                    }));
                });
            }
        }

        private void CbHall_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (cbHall.SelectedValue != null)
            {
                cfa.AppSettings.Settings["hallID"].Value = cbHall.SelectedValue.ToString();
                cfa.Save();
                hallID = (int)cbHall.SelectedValue;
            }
        }

        private void BtnSearchClose_Click(object sender, RoutedEventArgs e)
        {
            SearchBox.Visibility = Visibility.Collapsed;
            //this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => { Keyboard.Focus(txtScan); }));
        }

        private void BtnSearch_Click(object sender, RoutedEventArgs e)
        {
            var hallID = (int)cbSearchHall.SelectedValue;
            var mealID = (int)cbSearchMealTime.SelectedValue;
            _loading.Visibility = Visibility.Visible;
            string msg = "";
            Task task = new Task(new Action(delegate {
                pageIndex = 1;
                msg = GetData(pageIndex, hallID, mealID);
            }));
            task.Start();
            task.ContinueWith((t) => {
                _loading.Dispatcher.Invoke(new Action(delegate {
                    txtPageIndex.Text = pageIndex.ToString();
                    _loading.Visibility = Visibility.Collapsed;
                    message.Content = msg;
                    SearchBox.Visibility = Visibility.Collapsed;
                }));
                //this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => { Keyboard.Focus(txtScan); }));
            });
        }

        private void WTakeFoodSystem_Closed(object sender, EventArgs e)
        {
            listener.Stop();
        }
    }
}
